package com.zhoujing.cinema.backend.controller;

import com.github.pagehelper.PageInfo;
import com.zhoujing.cinema.constants.Constant;
import com.zhoujing.cinema.entity.*;
import com.zhoujing.cinema.service.UserService;
import com.zhoujing.cinema.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * @author ：ywj
 * @date ：Created in 2020/1/31 20:40
 * @description：用户的controller
 * @modified By：
 * @version: $
 */
@RequestMapping("/backend/user")
@Controller
public class UserController {
    @Autowired
    public UserService userService;
    @RequestMapping("/goLogin")
    public String goLogin(){
        return "login";
    }

    @RequestMapping("/goMain" )
    public String login(@CookieValue(value = "userId") Integer userId, Model model){
        if(ObjectUtils.isEmpty(userId)){
            return "login";
        }
        User user = userService.findUserById(userId);
        model.addAttribute("user",user);
        return "main";
    }
    @ResponseBody
    @RequestMapping("/loginByUsername")
    public ResponseResult loginByUsername(String username, String password, HttpServletResponse response){
        User user = userService.findUserByName(username);
        ResponseResult responseResult = new ResponseResult();
        if(user==null){
            responseResult.setStatus(Constant.RESPONSE_STATUS_FAILURE);
            responseResult.setData("");
            responseResult.setMessage("用户不存在");
        }else{
            if(!user.getPassword().equals(password)){
                responseResult.setStatus(Constant.RESPONSE_STATUS_FAILURE);
                responseResult.setData("");
                responseResult.setMessage("密码错误");
            }else{
                if(Integer.parseInt(user.getIs_staff())==0){
                    responseResult.setStatus(Constant.RESPONSE_STATUS_FAILURE);
                    responseResult.setData("");
                    responseResult.setMessage("您没有权限");
                }else{
                    responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
                    responseResult.setData(user);
                    responseResult.setMessage("登录成功");
                    Cookie cookie = new Cookie("userId",user.getId().toString());
                    cookie.setMaxAge(60 * 60);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        return responseResult;
    }
    @RequestMapping("/changeRole" )
    @ResponseBody
    public ResponseResult changeRole(Integer id,String status){
        ResponseResult responseResult = new ResponseResult();
        User user = new User();
        user.setId(id);
        user.setIs_staff(status);
        userService.changeRole(user);
        responseResult.setMessage("查询成功");
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        return responseResult;
    }
    @RequestMapping("/user" )
    public String user(Model model,Integer pageNum){
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum=Constant.PAGE_NUM;
        }
        PageInfo<User> user = userService.selectAllUser(pageNum,Constant.PAGE_SIZE);
        model.addAttribute("users",user);
        return "user";
        //System.out.println(username+password);
    }
    @RequestMapping("/searchUser" )
    @ResponseBody
    public ResponseResult searchUser(Integer pageNum,String username){
        ResponseResult responseResult = new ResponseResult();
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum=Constant.PAGE_NUM;
        }
        PageInfo<User> user = userService.searchUser(username,pageNum,Constant.PAGE_SIZE);
        responseResult.setData(user);
        responseResult.setMessage("查询成功");
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        return responseResult;
        //System.out.println(username+password);
    }
    @RequestMapping("/type")
    public String type(Model model,Integer pageNum){
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum=Constant.PAGE_NUM;
        }
        PageInfo<Type> list = userService.selectAllType(pageNum,Constant.PAGE_SIZE);
        model.addAttribute("type",list);
        return "type";
    }
    @RequestMapping("/area")
    public String area(Model model,Integer pageNum){
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum=Constant.PAGE_NUM;
        }
        PageInfo<Country> list = userService.selectAllArea(pageNum,Constant.PAGE_SIZE);
        model.addAttribute("area",list);
        return "area";
    }
    @RequestMapping("/year")
    public String year(Model model,Integer pageNum){
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum=Constant.PAGE_NUM;
        }
        PageInfo<Year> list = userService.selectAllYear(pageNum,Constant.PAGE_SIZE);
        model.addAttribute("year",list);
        return "year";
    }
    @RequestMapping("/addType")
    @ResponseBody
    public ResponseResult addCity(String cityName){
        ResponseResult responseResult = new ResponseResult();
        Type type = new Type();
        type.setType_name(cityName);
        userService.insertType(type);
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        return responseResult;
    }
    @RequestMapping("/updateType")
    @ResponseBody
    public ResponseResult updateType(String cityName,Integer cityId){
        ResponseResult responseResult = new ResponseResult();
        Type type = new Type();
        type.setType_name(cityName);
        type.setType_id(cityId);
        userService.updateType(type);
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        return responseResult;
    }
    @RequestMapping("/addArea")
    @ResponseBody
    public ResponseResult addArea(String cityName){
        ResponseResult responseResult = new ResponseResult();
        Country country = new Country();
        country.setCountry_name(cityName);
        userService.insertArea(country);
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        return responseResult;
    }
    @RequestMapping("/updateArea")
    @ResponseBody
    public ResponseResult updateArea(String cityName,Integer cityId){
        ResponseResult responseResult = new ResponseResult();
        Country country = new Country();
        country.setCountry_name(cityName);
        country.setCountry_id(cityId);
        userService.updateArea(country);
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        return responseResult;
    }
    @RequestMapping("/addYear")
    @ResponseBody
    public ResponseResult addYear(String cityName){
        ResponseResult responseResult = new ResponseResult();
        Year year = new Year();
        year.setYear_name(cityName);
        userService.insertYear(year);
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        return responseResult;
    }
    @RequestMapping("/updateYear")
    @ResponseBody
    public ResponseResult updateYear(String cityName,Integer cityId){
        ResponseResult responseResult = new ResponseResult();
        Year year = new Year();
        year.setYear_name(cityName);
        year.setYear_id(cityId);
        userService.updateYear(year);
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        return responseResult;
    }
    @RequestMapping("/banner")
    public String banner(Model model,Integer pageNum){
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum=Constant.PAGE_NUM;
        }
        List<Movie> jobs = userService.selectAllMovies();
        PageInfo<Banner> list = userService.selectAllBanner(pageNum,Constant.PAGE_SIZE);
        model.addAttribute("banner",list);
        model.addAttribute("movies",jobs);
        return "banner";
    }
    @ResponseBody
    @RequestMapping("/addBanner")
    public ResponseResult addBanner(HttpServletRequest request){
        ResponseResult responseResult = new ResponseResult();
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest mreq = resolver.resolveMultipart(request);
        MultipartFile file = mreq.getFile("avatar");
        Banner banner = new Banner();
        if(file!=null){
            String fileName = file.getOriginalFilename();
            //上传图片
            String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
            String avatars = "http://127.0.0.1:8088/basic/" + newFileName;
            banner.setUrl(avatars);
            try {
                File fileMkdir = new File("D:\\images\\basic");
                if (!fileMkdir.exists()) {
                    fileMkdir.mkdir();
                }
                //定义输出流 将文件保存在D盘    file.getOriginalFilename()为获得文件的名字
                FileOutputStream os = new FileOutputStream(fileMkdir.getPath() + "\\" + newFileName);
                InputStream in = file.getInputStream();
                int b = 0;
                while ((b = in.read()) != -1) { //读取文件
                    os.write(b);
                }
                os.flush(); //关闭流
                in.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String id = mreq.getParameter("id");
        String ids = mreq.getParameter("ids");
        String is_show = mreq.getParameter("is_show");
        if(ObjectUtils.isEmpty(ids)){
            banner.setIs_show(is_show);
            banner.setMovie_id(Integer.parseInt(id));
            userService.addBanner(banner);
            responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
            responseResult.setMessage("添加成功");
        }else{
            if(banner.getUrl()==""||banner.getUrl()==null){
                banner.setIs_show(is_show);
                banner.setId(Integer.parseInt(ids));
                banner.setMovie_id(Integer.parseInt(id));
                userService.updateBanner1(banner);
                responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
                responseResult.setMessage("修改成功");
            }else{
                banner.setIs_show(is_show);
                banner.setId(Integer.parseInt(ids));
                banner.setMovie_id(Integer.parseInt(id));
                userService.updateBanner(banner);
                responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
                responseResult.setMessage("修改成功");
            }
        }
        return responseResult;
    }
    @RequestMapping("/changeRole1" )
    @ResponseBody
    public ResponseResult changeRole1(Integer id,String status){
        ResponseResult responseResult = new ResponseResult();
        Banner banner = new Banner();
        banner.setId(id);
        banner.setIs_show(status);
        userService.changeRole1(banner);
        responseResult.setMessage("查询成功");
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        return responseResult;
    }
}
